using System;
using System.ComponentModel;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Net;
using System.Text;


namespace Puzzlepart.SharePoint.WebParts
{
    [ToolboxItemAttribute(false)]
    public class ContentLinkWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {

        private string _contentLink = null;
        [WebDisplayName("Content Link"),
         Category("Settings"),
         DefaultValue(""),
         WebBrowsable(true),
         Personalizable(PersonalizationScope.Shared)]
        public string ContentLink
        {
            get { return _contentLink; }
            set { _contentLink = value; }
        }

        protected override void CreateChildControls()
        {
            string contentUrl = _contentLink;
            try
            {
                if (String.IsNullOrEmpty(_contentLink)==false)
                {
                    SPWeb web = SPContext.Current.Web;

                    if(Uri.IsWellFormedUriString(_contentLink, UriKind.Relative))
                    {
                        if (contentUrl.StartsWith("/") == false) 
                            contentUrl = "/" + contentUrl;
                    
                        string serverUrl = web.Url;
                        if(web.ServerRelativeUrl.Equals("/")==false)
                            serverUrl = web.Url.Substring(0, web.Url.LastIndexOf(web.ServerRelativeUrl));
                        contentUrl = serverUrl + _contentLink;
                    }
                    
                    WebRequest request = WebRequest.Create(contentUrl);
                    request.Credentials = CredentialCache.DefaultCredentials;
                    using(WebResponse response = request.GetResponse())
                    {
                        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                        {
                            this.Controls.Add(new LiteralControl(stream.ReadToEnd()));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Label msg = new Label()
                {
                    Text = String.Format("An error occurred for ContentLink {0}: {1}", contentUrl, ex.Message),
                    ToolTip = ex.ToString()
                };
                Controls.Add(msg);
            }


        }
    }
}
